// yb_shop/pages/card_poster/index.js
var app = getApp();
let wechat = require("../..//utils/wechat.js");
var core = require("../..//utils/core.js");

Page({
  /**
   * 页面的初始数据
   */
  data: {
    src: '',
    paths: {
      card: 'yb_mingpian/pages/cardinfo/index',
    },
    config: app.config
  },

  // 保存图片
  dosave: function() {
    if (this.data.src.length > 0) {
      wx.showLoading({title:'保存中...'});
      wechat.saveImageToPhotosAlbum(this.data.src).then(d => {
        wx.hideLoading();
        core.alert("海报保存成功");
      }).catch(e => {
        wx.hideLoading();
        core.alert("海报保存失败,请重试");
      })
    } else {
      core.alert("海报正在生成,请稍候");
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var path = this.data.paths[options.share_type];
    var id = options.card_id;
    console.log("options",options);
    if (!options.avatar) {
      options.avatar = 'http://p.qlogo.cn/bizmail/H5GGghYv4DqmQlu5yEfZYRqMqFLnJXOicf4uoVJ0q15VMxTB2DMlulw/0';
    }

    var pic_url = app.util.makeurl({
      url: 'entry/wxapp/net_img', data: {
        url: encodeURIComponent(options.avatar)
      }
    });
      console.log("pic_url",pic_url);

      // 获取设备系统信息
      wx.getSystemInfo({
          success: function (res) {
              console.log("card_dev_info",res);
              if (res.platform == "devtools" || res.platform == "android") {
                  options.avatar = pic_url;
              }
          }
      })

    //options.avatar = pic_url;

    const ctx = wx.createCanvasContext('poster');
    ctx.clearRect(0, 0, 0, 0); 

    ctx.setFillStyle('#ffffff')
    ctx.fillRect(0, 0, 750, 1100)
    const CONTENT_ROW_LENGTH = 30;  // 正文 单行显示字符长度15个字

    //姓名
    var user_name = options.user_name;
    if (user_name){
      let [contentLeng, contentArray, contentRows] = this.textByteLength(user_name, CONTENT_ROW_LENGTH);
      ctx.setTextAlign('center')
      ctx.setFontSize(48);
      ctx.setFillStyle("#080808");
      if (contentArray.length == 1) {
        ctx.fillText(contentArray[0], 380, 220);
      } else {
        ctx.fillText(contentArray[0] + '...', 380, 220);
      }
    }

    //职位
    var position = options.position;
    if (position){
      let [contentLeng, contentArray, contentRows] = this.textByteLength(position, CONTENT_ROW_LENGTH);
      ctx.setTextAlign('center')

      ctx.setFontSize(30);
      ctx.setFillStyle("#333333");
      if (contentArray.length == 1) {
        ctx.fillText(contentArray[0], 380, 280);
      } else {
        ctx.fillText(contentArray[0] + '...', 380, 280);
      }
    }

    ctx.fillText("长按识别二维码", 380, 1000);

    var url = app.util.makeurl({url:'entry/wxapp/qr_code',data:{
      path: path,
      scene: id
    }});

    var md5 = app.util.md5("share_type=" + options.share_type + "&card_id=" + options.card_id);
    var qrcode_path = app.getCache(md5);
    console.log("qrcode_path",qrcode_path);
    
    var that = this;
    if (qrcode_path != "") {
      console.log("has save !!!!!!!");
      ctx.drawImage(qrcode_path, 30, 320, 680, 650);
      wechat.downloadFile(options.avatar)
        .then(d => {
          console.log(d);
          ctx.drawImage(d.tempFilePath, 310, 0, 150, 150);
          
          ctx.draw(false, function () {
            setTimeout(() => {
              wx.canvasToTempFilePath({
                destWidth: 750,
                destHeight: 1050,
                canvasId: 'poster',
                success: function (res) {
                  console.log(res.tempFilePath)
                  that.setData({
                    src: res.tempFilePath
                  });
                }
              })
            }, 200)
          });
      })
      .catch(err => {
        core.alert("图片无法下载,海报生成失败");
      })
    } else {
      console.log("not save !!!!!!!");

      wechat.downloadFile(options.avatar)
      .then(d => {
          console.log(d);
        ctx.drawImage(d.tempFilePath, 310, 0, 150, 150);
        return wechat.downloadFile(url);
      }).then(d => {
        console.log(d);
        return wechat.saveFile(d.tempFilePath);
      })
      .then(d => {
        console.log(d);
        var savedFilePath = d.savedFilePath;
        app.setCache(md5, savedFilePath, 30);
        ctx.drawImage(savedFilePath, 30, 320, 680, 650);
        ctx.draw(false,function(){
          setTimeout(() => {
            wx.canvasToTempFilePath({
              destWidth: 750,
              destHeight: 1100,
              canvasId: 'poster',
              success: function (res) {
                console.log(res)
                that.setData({
                  src: res.tempFilePath
                });
              }
              })
            }, 200)
          });
      })
      .catch(err => {
        core.alert("图片无法下载,海报生成失败");
      })
     }
  },

  textByteLength: function(text, num) {  // text为传入的文本  num为单行显示的字节长度
    let strLength = 0; // text byte length
    let rows = 1;
    let str = 0;
    let arr = [];
    for (let j = 0; j < text.length; j++) {
      if (text.charCodeAt(j) > 255) {
        strLength += 2;
        if (strLength > rows * num) {
          strLength++;
          arr.push(text.slice(str, j));
          str = j;
          rows++;
        }
      } else {
        strLength++;
        if (strLength > rows * num) {
          arr.push(text.slice(str, j));
          str = j;
          rows++;
        }
      }
    }
    arr.push(text.slice(str, text.length));
    return [strLength, arr, rows]   //  [处理文字的总字节长度，每行显示内容的数组，行数]
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  }
})